package com.nuatar.meibi;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.nuatar.meibi.Thread.DownloadListener;
import com.nuatar.meibi.Thread.MultiDownloader;
import com.nuatar.meibi.pubvar.MyThread;
import android.content.res.Configuration;

import com.nuatar.meibi.pubvar.Configer;
import com.nuatar.meibi.pubvar.ImagePair;
import com.nuatar.meibi.pubvar.PhoneMaster;
import com.nuatar.meibi.pubvar.PostMan;
import com.nuatar.meibi.pubvar.WallPaper;
import com.nuatar.meibi.scoll.MyXZ;
import com.nuatar.meibi.scoll.MyXZ.ImageGetter;
import com.nuatar.meibi.scoll.ZoomListener;
import com.nuatar.meibi.scoll.ZoomListener.Swiper;
import com.tencent.exmobwin.banner.TAdView;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class ImageShow extends FatherActivity {
	public static Handler mhandler;
	public static Handler phandler;
	TAdView tad;
	MyXZ mx;
	TextView tv;
	TextView ProgressTitle;
	int Tlength = 0;
	int achor;
	List<MyThread> mt;
	public WallPaper wp;
	MeiBi mks;
	String flist = "";
	int curr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_show);
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(this);
		tv = (TextView) findViewById(R.id.ImageTittle);
		mx = (MyXZ) findViewById(R.id.myXZ1);
		ProgressTitle = (TextView) findViewById(R.id.ProgressTitle);
		mks = (MeiBi) getApplication();
		wp = mks.CurrentPaper;
		curr = mks.Curr;
		Tlength = wp.BigImages.length;
		ImageGetter ig = new ImageGetter() {
			@Override
			public void Update(View v) {
				Myson ms = new Myson(wp.id, curr, wp.BigImages[curr]);
				new Thread(ms).start();
			}
		};
		mhandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int i = msg.what;
				if (curr == i) {
					ProgressTitle.setVisibility(View.GONE);
					mx.setImage(wp.id, wp.BigImages[curr]);
					tv.setText(curr + 1 + "/" + Tlength);
					int bbs;
					if (achor < 0) {
						bbs = curr - 1 < 0 ? 0 : curr - 1;
					} else {
						bbs = curr + 1 >= Tlength ? Tlength - 1 : curr + 1;
					}
					Myson ms = new Myson(wp.id, bbs, wp.BigImages[bbs]);
					new Thread(ms).start();
				}
			}
		};
		mx.setImageGetter(ig);
		phandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == curr) {
					ProgressTitle.setVisibility(View.VISIBLE);
					Bundle b = msg.getData();
					int son = b.getInt("son");
					int mom = b.getInt("mom");
					float rd = (float) son / (float) mom * 100;
					String re = new java.text.DecimalFormat("#.00").format(rd)
							+ "%";
					ProgressTitle.setText("下载：" + re);
				}
			}
		};

		mx.setImage(wp.id, wp.BigImages[curr]);
		tv.setText(curr + 1 + "/" + Tlength);
		Swiper swp = new Swiper() {
			@Override
			public void Swipe(View v, float length) {
				if (Math.abs(length) > 15) {
					int i = length > 0 ? 1 : -1;
					achor = i;
					int Curr = curr + i;
					if (Curr < 0) {
						Curr = Tlength - 1;
					} else if (Curr >= Tlength) {
						Curr = 0;
					}
					curr = Curr;
					ProgressTitle.setVisibility(View.GONE);
					((MyXZ) v).setImage(wp.id, wp.BigImages[curr]);
					tv.setText(curr + 1 + "/" + Tlength);
				}

			}
		};
		tad=(TAdView) findViewById(R.id.adview);
		MeiBi mk = (MeiBi) this.getApplication();
		ZoomListener zl = new ZoomListener(swp);
		mx.setOnTouchListener(zl);
		
	}
	@Override
	protected void onStart() {
		super.onStart();
		mGaTracker.sendView(MainActivity.class.toString());
	}

	@Override
	protected void onDestroy() {
		mx.recycleImage();
		Log.i("On", "Destory");
		super.onDestroy();

	}

	class Myson extends MyThread {
		String id;
		int i;
		ImagePair ip;

		public Myson(String ids, int isd, ImagePair ips) {
			id = ids;
			i = isd;
			ip = ips;
		}

		@Override
		public void run() {
			// TODO Myson-run执行体
			if (flist.indexOf(i + ",") < 0) {
				flist += i + ",";
				final int pson = i;
				DownloadListener dl = new DownloadListener() {

					@Override
					public void ReportProcess(int son, int mom) {
						// TODO 自动生成的方法存根
						Message msg = new Message();
						msg.what = pson;
						Bundle b = new Bundle();
						b.putInt("son", son);
						b.putInt("mom", mom);
						msg.setData(b);
						ImageShow.phandler.sendMessage(msg);
					}

					@Override
					public void DownloadResult(boolean result) {
						// TODO 自动生成的方法存根
						if (result) {
							ImageShow.mhandler.sendEmptyMessage(i);
							flist = flist.replaceAll(i + "", "");
						}
					}

					@Override
					public void ErrorLog(Exception e) {
						// TODO 自动生成的方法存根
						TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
						String imei = PhoneMaster.getMD5Str(telephonyManager
								.getDeviceId());
						StringWriter sw = new StringWriter();
						PrintWriter pw = new PrintWriter(sw);
						e.printStackTrace(pw);
						String info = pw.toString();
						Map<String, String> params = new HashMap<String, String>();
						params.put("info", info);
						params.put("did", imei);
						params.put("softid", "MMK-ER");
						PostMan.submitPostData(params, "utf-8", "action=PostEr");
					}
				};
				String httpUrl = PhoneMaster.getURLFromId(id, ".bdt");
				String savePath = PhoneMaster.getFilePathFromId(id, ".bdt");
				URL url;
				try {
					url = new URL(httpUrl);
					MultiDownloader mdl = new MultiDownloader(url, savePath, 3,
							dl, ip);
					mdl.Start();
				} catch (MalformedURLException e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				}
			}
		}

	}

	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		String title = (String) item.getTitle();
		if (title == this.getResources().getText(R.string.setWall)) {
			MeiBi mks = (MeiBi) getApplication();
			Bitmap bmp = mx.getImage();
			if (bmp != null) {
				WallpaperManager wm = WallpaperManager.getInstance(this);
				try {
					wm.setBitmap(bmp);
					Toast.makeText(getApplicationContext(), "壁纸设置成功",
							Toast.LENGTH_SHORT).show();
				} catch (IOException e) {

					Toast.makeText(getApplicationContext(), "设置失败",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getApplicationContext(), "图片未缓冲完成，请稍候",
						Toast.LENGTH_SHORT).show();
			}
		}else if(title == this.getResources().getText(R.string.Share)) {
			ImagePair ip=wp.BigImages[mks.Curr];
			String sourcePath=PhoneMaster.getFilePathFromId(wp.id, ".bdt");
			String uuid=UUID.randomUUID().toString().replaceAll("-", "");
			String savePath=Environment.getExternalStorageDirectory().getPath()
					+ Configer.DirHead+uuid+".jpg";
			FileOutputStream fs;
			try {
				fs = new FileOutputStream(savePath);
				fs.write(PhoneMaster.getFileByteArray((new File(sourcePath)), ip.Seeker, ip.Length));
				fs.flush();
				fs.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String Content=(String) this.getResources().getText(R.string.Content);
			Uri uri=Uri.fromFile(new File(savePath));
			share(Content,uri);
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.image_show, menu);

		return true;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	private void share(String content, Uri uri) {
		Intent intent = new Intent(Intent.ACTION_SEND);
		if (uri != null) {
			intent.putExtra(Intent.EXTRA_STREAM, uri);
			intent.setType("image/*");
			intent.putExtra("sms_body", content);

		} else {
			intent.setType("text/plain");
		}
		intent.putExtra(Intent.EXTRA_TEXT, content);
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享");  
		intent.putExtra(Intent.EXTRA_TITLE, "我是标题");    
		startActivity(Intent.createChooser(intent, "请选择分享方式")); 
	}
}
